import { StateType } from '@/App';
import store from '@/store';
import { Toast } from 'antd-mobile';
import axios from 'axios';
import history from './history';
import { getToken, removeToken, setToken } from './local';

// 请求基地址
export const baseURL = 'http://geek.itheima.net';

const http = axios.create({
  baseURL: baseURL,
  timeout: 5000,
});

// 请求拦截器
http.interceptors.request.use(
  function (config) {
    const { token } = getToken();
    if (config.headers && token) {
      // 2. 设置config
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

// 响应拦截器
http.interceptors.response.use(
  function (response) {
    return response.data;
  },
  async function (error) {
    console.dir(error);
    if (!error.response) {
      Toast.show({ content: '网络错误' });
      return Promise.reject(error);
    }
    if (error.response.status === 401) {
      if (getToken().refresh_token) {
        // 1. 包在try catch语句，捕获到错误，就重定向到登录界面
        try {
          const res = await axios({
            url: baseURL + '/v1_0/authorizations',
            method: 'put',
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded',
              Authorization: `Bearer ${getToken().refresh_token}`,
            },
          });
          console.log('axios', res);
          //无感刷新 重新缓存token
          const auth = {
            token: res.data.data.token,
            refresh_token: getToken().refresh_token,
          };
          store.dispatch({
            type: 'login/token',
            payload: auth,
          });
          setToken(auth);
          //重新发上次的请求 更新
          return http(error.config);
        } catch (err) {
          // 两个token都无效了 直接跳转登录 清除数据
          removeToken();
          store.dispatch({
            type: 'login/token',
            payload: {} as any,
          });
          history.push('/login', {
            from: history.location.pathname,
          } as StateType);
        }
      }
      Toast.show({ content: '登录超时' });
      history.push('/login', { from: history.location.pathname } as StateType);
    } else {
      Toast.show({ content: error.response.data?.message });
    }
    return Promise.reject(error);
  }
);
export default http;
